<?php
namespace app\index\model;
use think\Db;
use think\Model;

class SubUser extends Model
{
	public function getTestQuesIds($tId, $quesIds = [], $status = ''){
		$user = user();
		return self::where('user_id',$user['id'])->where('t_id',$tId)
					->when($quesIds, function($query) use ($quesIds){
						$query->where('ques_id', 'in', $quesIds);
					})
					->when($status, function($query) use ($status){
						$query->where('status', $status);
					})->column('ques_id,status');
	}

	public function getTestQues($tId,$quesId){
		$user = user();
		$where = ['user_id'=>$user['id'], 'ques_id'=>$quesId];
		if($tId) $where['t_id'] = $tId;
		$data = self::where($where)->find();
		if($data) $data['answer'] = json_decode($data['answer'],true);
		return $data;
	}

	public function disposeUserQues($tId,$quesId,$answer,$status){
		$user = user();
		$data = self::where('user_id',$user['id'])->where('ques_id',$quesId)->find();
		if($data){
			self::where('user_id',$user['id'])->where('ques_id',$quesId)->update([
				't_id' => $tId,
				'answer' => json_encode($answer),
				'status' => $status,
				'times' => $data['times']+1,
				'last_time' => time(),
			]);
		}else{
			self::insert([
				't_id' => $tId,
				'ques_id' => $quesId,
				'user_id' => $user['id'],
				'start_time' => time(),
				'answer' => json_encode($answer),
				'status' => $status,
				'times' => $data['times']+1,
				'last_time' => time(),
			]);
		}
	}

	public function question()
	{
		return $this->hasOne('SubQuestion','id','ques_id');
	}
}